/* 
 * Copyright 2009 Shared Object (www.sharedobject.ch)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package edos.prm.util;

/**
 * A {@code VersionNumber} is a value of form "x.y" or "x.y.z".
 * <p>
 * It has the form of a {@code major} number, a {@code minor} number followed
 * by an optional {@code revision} number.
 * 
 * @author Ciaran Bryce
 * @version 1.0
 */
public final class VersionNumber implements Comparable<VersionNumber> {

	private int major;
	private int minor;
	private int revision;

	public VersionNumber(String number) throws NumberFormatException {
		String[] values = number.trim().split("\\.");
		if ( ( values.length != 2 ) && ( values.length != 3 ) )
			throw new NumberFormatException("Format must be x.y or x.y.z");
		major = Integer.parseInt(values[0]);
		minor = Integer.parseInt(values[1]);
		if ( values.length == 3 ) 
			revision = Integer.parseInt(values[2]);
		else
			revision = 0;
	}

	
	public int compareTo(VersionNumber obj) {
		VersionNumber number = (VersionNumber)obj;
		if ( number.major < this.major )
			return -1;
		if ( number.major > this.major )
			return 1;
		// Same major number
		if ( number.minor < this.minor )
			return -1;
		if ( number.minor > this.minor )
			return 1;
		// Same minor number
		return (number.revision - this.revision);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + major;
		result = prime * result + minor;
		result = prime * result + revision;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final VersionNumber other = (VersionNumber) obj;
		if (major != other.major)
			return false;
		if (minor != other.minor)
			return false;
		if (revision != other.revision)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return major + "." + minor + "." + revision;
	}

	public int getMajorNumber() {
		return major;
	}

	public int getMinorNumber() {
		return minor;
	}

	public int getRevisionNumber() {
		return revision;
	}
}
